<template>
  <canvas
    ref="captcha"
    title="点击图片更换验证码"
  ></canvas>
</template>

<script>
import {onMounted} from "vue";
import EsAjax from "@/utils/EsAjax";
import ApiUrls from "@/apis";

/**
 * 图形验证码组件
 * @version 1.0.0
 */
export default {
  name: "CaptchaImage",
  props: {
    // 图片宽度
    width: { type: Number, default: 150 },
    // 图片高度
    height: { type: Number, default: 39 },
    // 边框圆角
    round: { type: Number, default: 2 },
    // 字符集
    codeSet: {
      type: Array,
      default() {
        return [..."2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY"];
      },
    },
    // 验证码字体
    fontTtf: { type: String, default: "微软雅黑" },
    // 验证码字体大小(px)
    fontSize: { type: String, default: "23px" },
    // 验证码过期时间（s）
    expire: { type: Number, default: 1800 },
    // 验证码位数
    length: { type: Number, default: 4 },
    // 是否添加杂点
    useNoise: { type: Boolean, default: true },
    // 是否画混淆曲线
    useCurve: { type: Boolean, default: true },
    // 背景颜色
    background: { type: String, default: "white" },
    // 是否输出调试信息
    isDebug: { type: Boolean, default: false },
    // 超级代码
    superCode: { type: String, default: "o01l" },
  },
  data() {
    return {};
  },
  methods: {


 getViewCode (){
  //获取验证码

},
    // 实例化组件
    initializeComponent() {
      this.$refs.captcha.style.cssText = `width:${this.width}px; height:${this.height}px; border-radius:${this.round}px;`;
      let characters = [];
      this.draw(this.$refs.captcha, characters);
      this.log(characters);
      this.$refs.captcha.onclick = () => {
        this.draw(this.$refs.captcha, characters);
        this.log(characters);
      };
      this.value = characters.join("").trim();
      return characters;
    },
    /**
     * 刷新验证码
     */
    refresh() {
      this.log("refresh");
      this.initializeComponent();
    },
    /**
     * 检测验证码是否正确
     * @param {String} text 验证码
     * @param {Boolean} ignoreCase 是否忽略大小写
     */
    check(text, ignoreCase = true) {
      if (text == this.superCode) {
        return true;
      }
      let result = false;
      if (ignoreCase) {
        result =
          text.length > 0 && text.toLowerCase() == this.value.toLowerCase();
      } else {
        result = text.length > 0 && text == this.value;
      }
      this.log("text=", text, "&value=", this.value, "&result=", result);
      return result;
    },
    log(...args) {
      if (this.isDebug) {
        console.log("[ImageCaptcha] ", ...args);
      }
    },
    // 绘制图形验证码
    draw(el, characters) {
      let width = el.clientWidth;
      let height = el.clientHeight;
      el.width = width;
      el.height = height;
      let context = el.getContext("2d");
      if (this.background) {
        //绘制矩形，作背景色
        context.fillStyle = this.background;
        //绘制实心矩形
        context.fillRect(0, 0, width, height);
      }
      let codeSet = this.codeSet;
      //codeSet = [...'们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高'];
      //codeSet = [...'量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全'];
      //codeSet = [...'组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立'];
      //codeSet = [...'题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复'];
      //codeSet = [...'安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术'];
      //codeSet = [...'状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记'];
      let sLength = codeSet.length;
      // 验证码字体样式
      let fontStyle = `bold ${this.fontSize} ${this.fontTtf}`;
      // 验证码位数
      let len = this.length;
      for (let i = 0; i < len; i++) {
        let j = Math.floor(Math.random() * sLength); // 随机索引
        let deg = (Math.random() * 30 * Math.PI) / 180; // 0-30随机弧度
        let text = codeSet[j]; // 随机字符
        characters[i] = text;
        let x = 10 + i * 20; // x坐标
        let y = 20 + Math.random() * 8; // y坐标
        // 位移，旋转角度，颜色，文字，样式，起始位置
        context.font = fontStyle;
        context.translate(x, y);
        context.rotate(deg);
        context.fillStyle = this.randomColor();
        context.fillText(text, 0, 0);
        // 复位
        context.rotate(-deg);
        context.translate(-x, -y);
      }
      // 添加杂点
      if (this.useNoise) {
        for (let i = 0; i <= 30; i++) {
          context.strokeStyle = this.randomColor();
          context.beginPath(); // 开始路径
          let m = Math.random() * width;
          let n = Math.random() * height;
          context.moveTo(m, n);
          context.lineTo(m + 1, n + 1);
          context.stroke(); // 画出上面定义好的路径
        }
      }

      if (this.useCurve) {
        for (let i = 0; i < 8; i++) {
          context.strokeStyle = this.randomColor();
          context.beginPath();
          context.moveTo(Math.random() * width, Math.random() * height);
          context.lineTo(Math.random() * width, Math.random() * height);
          context.stroke();
        }
      }
    },
    // 生成随机颜色
    randomColor() {
      let rgb = {
        r: Math.floor(Math.random() * 256),
        g: Math.floor(Math.random() * 256),
        b: Math.floor(Math.random() * 256),
      };
      return `rgb(${rgb.r},${rgb.g},${rgb.b})`;
    },
  },
  mounted() {
    this.initializeComponent();
  },
};
</script>

<style>
</style>
